/*
 * Obj.java
 *
 * Created on 25 aprile 2007, 6.16
 *.
 */

package net.ermannofranco.genericdaojdbc.util;

import java.util.Collection;
import java.util.Map;

/**
 * Controlla la validita' di un oggetto, se non sia nullo o vuoto.
 * 
 * @author ermanno
 * @version $Id: Obj.java 6 2010-03-29 20:50:09Z ermanno.franco $
 */
public class Obj {

	/** Creates a new instance of Obj */
	private Obj() {
	}

	public static boolean isValid(Object value) {
		if (value == null)
			return false;
		else if (value.getClass().isArray()) {
			// chissa' se l'autoboxing ci aiuta in caso di array di primitive?
			if (value.getClass().getComponentType() == int.class) {
				return ((int[]) value).length > 0;
			} else if (value.getClass().getComponentType() == short.class) {
				return ((short[]) value).length > 0;
			} else if (value.getClass().getComponentType() == byte.class) {
				return ((byte[]) value).length > 0;
			} else if (value.getClass().getComponentType() == long.class) {
				return ((long[]) value).length > 0;
			} else if (value.getClass().getComponentType() == boolean.class) {
				return ((boolean[]) value).length > 0;
			} else if (value.getClass().getComponentType() == float.class) {
				return ((float[]) value).length > 0;
			} else if (value.getClass().getComponentType() == double.class) {
				return ((double[]) value).length > 0;
			} else if (value.getClass().getComponentType() == char.class) {
				return ((char[]) value).length > 0;
			} else {
				return ((Object[]) value).length > 0;
			}
		} else if (value instanceof Collection) {
			return ((Collection) value).size() > 0;
		} else if (value instanceof Map) {
			return ((Map) value).size() > 0;
		} else
			return value.toString().trim().length() > 0;
	}

	public static Object checkNull(Object o) {
		return o == null ? "<null>" : o;
	}

	public static int checkNull(Integer o) {
		return o == null ? 0 : o;
	}

	public static double checkNull(Double o) {
		return o == null ? 0.0 : o;
	}

}
